let socket = null
let messageCallback = null
let reconnectTimer = null
let urlCache = ''
let reconnectAttempts = 0 // ✅ 新增：记录当前重连次数
const MAX_RECONNECT_ATTEMPTS = 3 // ✅ 新增：最多重连3次

export function connectSocket(url, onMessage) {
  if (socket && socket.readyState === WebSocket.OPEN) return socket

  urlCache = url
  messageCallback = onMessage

  socket = new WebSocket(url)

  socket.onopen = () => {
    console.log('[WebSocket] 连接已建立')
    clearTimeout(reconnectTimer)
    reconnectAttempts = 0 // ✅ 成功后重置尝试次数
  }

  socket.onmessage = (event) => {
    try {
      const isJson = event.data?.startsWith('{') || event.data?.startsWith('[')
      const msg = isJson ? JSON.parse(event.data) : { content: event.data }
      messageCallback && messageCallback(msg)
    } catch (e) {
      console.error('[WebSocket] 消息处理异常：', event.data)
    }
  }

  socket.onclose = () => {
    console.warn(`[WebSocket] 已关闭，准备第 ${reconnectAttempts + 1} 次重连`)

    if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
      reconnectAttempts++
      reconnectTimer = setTimeout(() => {
        connectSocket(urlCache, messageCallback)
      }, 3000)
    } else {
      console.error('[WebSocket] 超过最大重连次数，停止重连')
    }
  }

  socket.onerror = (err) => {
    console.error('[WebSocket] 发生错误', err)
    if (socket.readyState !== WebSocket.CLOSED) {
      socket.close()
    }
  }

  return socket
}

export function sendSocketMessage(data) {
  if (socket && socket.readyState === WebSocket.OPEN) {
    socket.send(typeof data === 'string' ? data : JSON.stringify(data))
  } else {
    console.warn('[WebSocket] 当前未连接，消息未发送')
  }
}

export function closeSocket() {
  if (socket) {
    socket.onclose = null // 避免触发重连
    socket.close()
    socket = null
    clearTimeout(reconnectTimer)
    reconnectAttempts = 0 // ✅ 手动关闭时重置重连计数
  }
}
